package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.*;

import java.time.Instant;
import java.util.List;
import java.time.LocalDateTime;

@Mapper
public interface UserMapper extends BaseMapper<User> {

//    User selectById(String username);

    // 通过手机号和码密码查询方法
    @Select("SELECT * FROM user WHERE phone_number = #{phoneNumber} AND password = #{password}")
    User selectByPhoneAndPassword(String phoneNumber, String password);

    // 通过手机号查询方法
    @Select("SELECT * FROM user WHERE phone_number = #{phoneNumber}")
    User selectByPhone(String phoneNumber);

    //通过手机号删除用户
    @Delete("DELETE FROM user WHERE phone_number = #{phoneNumber}")
    boolean revokeUserByPhone(String phoneNumber);

    // 添加更新头像方法
    @Update("UPDATE user SET head = #{head} WHERE id = #{id}")
    int updateHeadById(Integer id, String head);

    // 添加更新基本信息方法
    @Update("UPDATE user SET nickname = #{nickname}, gender = #{gender}, age = #{age}, email = #{email} WHERE id = #{id}")
    int updateUserInfoById(Integer id, String nickname, String gender, Integer age, String email);

    // 添加更新密码方法
    @Update("UPDATE user SET password = #{newPassword} WHERE id = #{userId}")
    int updatePasswordById(Integer userId, String newPassword);

    // 查询活跃用户（与消息表关联）
    @Select("SELECT u.* FROM user u " +
            "WHERE u.id IN (SELECT DISTINCT user_id FROM chat_messages " +
            "WHERE chat_messages.created_at > #{cutoff})")
    List<User> selectActiveUsers(Instant cutoff);

    // 插入用户
    @Insert("INSERT INTO user(id, username, head, phone_number) " +
            "VALUES(#{id}, #{username}, #{head}, #{phoneNumber})")
    int insert(User user);

    // 更新用户信息
    @Update("UPDATE user SET username=#{username}, " +
            "head=#{head} WHERE id=#{id}")
    int update(User user);
}


